import React, { Component, ComponentClass } from 'react';
import Taro from '@tarojs/taro';
import {View, Image, Picker} from '@tarojs/components'
import {vcmonitor} from "../../../utils/tools";
import Confirm from "../../components/confirm/confirm";
import GzhAuth from "../../../components/gzh-auth/gzh-auth";
import {VERIFIER_TELLER_PAGE, VERIFIER_TELLER_CANEL, IDENTITY, RESOURCE_URL} from '../../../constants/api';
import {http} from '../../../utils/http'
import {user} from '../../../utils/user.service'
import NewIcon from '../../productForm/components/icon'
import './index.scss'

type PageOwnProps = {};
type PageState = {
  distributors: string
  checkerList: []
  keyId: string
  confirmShow: boolean
  formData: object
  supplierList: any
  supplierIndex: number
}

class Index extends Component {
  state: PageState = {
    distributors: '',
    checkerList: [],
    confirmShow: false,
    supplierIndex: 0,
    keyId: '',
    formData: {
      supplier_id: null,
      s: 10,
      p: 1
    },
    supplierList: [],
    pageStatus: true
  }

  onReachBottom() {
    const {formData}: any = this.state;
    formData.p = parseInt(formData.p) + 1;
    this.setState({
      formData
    }, () => this.getData());
  }

  async componentDidShow() {
    const isLogin = await user.checkLogin()
    if (!isLogin) {
      Taro.showToast({
        title: '你还未登录，请登录',
        icon: 'none',
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        user.jumpLogin()
      }, 1500)
      return
    }
    vcmonitor(this)
    const {formData}: any = this.state;
    formData.p = 1;
    this.setState({
      formData,
      pageStatus: true,
      checkerList: []
    }, async () => {
      const res = await http.HGet(IDENTITY);
      const supplierList = res.data.superCheckerList;
      this.setState({
        supplierList
      }, () => {
        this.onChange({
          detail: {
            value: 0
          }
        });
      });
    })
  }

  reset() {
    const {formData}: any = this.state;
    formData.p = 1;
    this.setState({
      formData,
      pageStatus: true,
      checkerList: []
    }, () => this.getData())
  }

  async getData() {
    let {checkerList, pageStatus, formData}: any = this.state;
    if (pageStatus == false) return;
    Taro.showLoading({title: '加载中...'});
    const res = await http.HGet(VERIFIER_TELLER_PAGE, formData)
    Taro.hideLoading();
    if (res) {
      checkerList = checkerList.concat(res.data);
      this.setState({
        checkerList
      });
      if (!res.data || res.data.length < 10) {
        this.setState({
          pageStatus: false
        });
      }
    }
  }

  // 提示框点击确定
  async confirmSuccess() {
    const res = await http.HPost(VERIFIER_TELLER_CANEL, {
      supplier_id: this.state.formData.supplier_id,
      keyId: this.state.keyId
    })
    this.reset()
    this.confirmClose();
  }

  // 提示框点击取消
  confirmCancel() {
    this.confirmClose();
  }

  // 提示框点击遮罩层
  confirmClose(isShow = false) {
    this.setState({
      confirmShow: isShow
    });
  }

  // 提示框点击遮罩层
  confirmOpen(id) {
    if (id) {
      this.setState({
        keyId: id
      })
    }
    this.setState({
      confirmShow: true
    });
  }

  onChange(e) {
    const {supplierList, formData}: any = this.state;
    const supplierIndex = Number(e.detail.value);
    const distributors = supplierList[supplierIndex].company;
    formData.supplier_id = supplierList[supplierIndex].supplier_id;
    formData.p = 1;
    this.setState({
      supplierIndex,
      distributors,
      formData,
      checkerList: [],
      pageStatus: true
    }, () => {
      this.getData();
    });
  }

  render() {
    const {checkerList, distributors, confirmShow, supplierList, supplierIndex, formData} = this.state;
    const {supplier_id} = formData;
    const dataColor = Taro.getStorageSync('colorData');
    return (
      <View className='cancel-after-management'>
        <GzhAuth />
        <View className='cancel-after-management-distributors'>
          <View className='cancel-after-management-distributors-text'>
            供应商：{distributors}
          </View>
          <Picker
            value={supplierIndex}
            range={supplierList}
            rangeKey='company'
            onChange={this.onChange.bind(this)}
            mode='selector'
          >
            <View
              className='cancel-after-management-distributors-btn'
              style={`border: solid 1px ${dataColor.titleColor}; color: ${dataColor.titleColor};`}
            >
              切换
            </View>
          </Picker>
        </View>
        {checkerList && checkerList.length > 0 && checkerList.map((info: any, index) =>
          <View className='cancel-after-management-info' key={index}>
            <View className='cancel-after-management-info-block'>
              <View className='cancel-after-management-info-block-head'>
                <Image src={info.photo} mode='widthFix' className='image' />
                {info.is_super == 1 &&
                <Image src={`${RESOURCE_URL}/resources/weapp/images/202110/superChecker.png`} className='image-icon' />}
              </View>
              <View className='cancel-after-management-info-block-info'>
                <View className='cancel-after-management-info-block-info-text m-b-10'>
                  <View className='text-length'>
                    {info.real_name ? `${info.real_name}/` : '-/'}{info.nick_name}{info.real_name ? `/${info.phone}` : '/-'}
                  </View>
                  {
                    info.gender == 1 ? <NewIcon color='#489BF7' font='12' className='icon iconfont icon-nan-01'
                      style='margin-left: 10px;'
                    ></NewIcon> :
                      <NewIcon font='12' color='#f00' className='icon iconfont icon-nv-01-01'
                        style='margin-left: 10px;'
                      ></NewIcon>
                  }
                </View>
                <View className='cancel-after-management-info-block-info-text area-cla'>地区：{info.address || ''}</View>
              </View>
              <View
                className='cancel-after-management-info-block-edit'
                style='border: solid 1px #aaa; color: #aaa;'
                onClick={() => Taro.navigateTo({
                  url: `/main/my/cancelAfterManagement/add?id=${supplier_id}&userId=${info.id}`
                })}
              >编辑</View>
              <View
                className='cancel-after-management-info-block-cancel'
                onClick={() => this.confirmOpen(info.id)}
                style={`border: solid 1px ${dataColor.titleColor}; color: ${dataColor.titleColor};`}
              >取消</View>
            </View>
          </View>
        )}
        <View className='cancel-after-management-add'>
          <View
            className={process.env.TARO_ENV === 'h5' ? "addInfo h5-small" : "addInfo"}
            style={`background-color: ${process.env.mainColor}`}
            onClick={() => Taro.navigateTo({
              url: `/main/my/cancelAfterManagement/add?id=${supplier_id}`
            })}
          >增加核销员 +</View>
        </View>
        {confirmShow && <Confirm
          width='70'
          content='是否确定取消该核销员身份'
          success={() => this.confirmSuccess()}
          cancel={() => this.confirmCancel()}
          close={() => this.confirmClose()}
        />}
      </View>
    );
  }
}

export default Index as ComponentClass<PageOwnProps, PageState>
